<template>
  <el-dialog :title="title" :visible.sync="visible">
    <el-form :model="deptInfo" label-position="right" label-width="80px">
      <el-form-item label="部门全称">
        <el-input v-model="deptInfo.fullname" placehoder="请输入部门全称"></el-input>
      </el-form-item>
      <el-form-item label="部门简称">
        <el-input v-model="deptInfo.simplename" placehoder="请输入部门简称"></el-input>
      </el-form-item>
      <el-form-item label="部门排序">
        <el-input v-model="deptInfo.num" placehoder="请输入排序值"></el-input>
      </el-form-item>
      <el-form-item label="上级部门">
        <el-cascader
          :options="deptList"
          :show-all-levels="false"
          :props="{label:'fullname',value:'id',emitPath:false,checkStrictly:true}"
          v-model="deptInfo.pid"></el-cascader>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="warning" @click="visible=false">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
const initInfo = {
  fullname: '',
  simplename: '',
  num: '',
  pid: '',
  id: ''
}
export default {
  name: 'DeptEdit',
  data () {
    return {
      title: '添加部门',
      visible: false,
      deptInfo: {},
      deptList: [],
      loading: {}
    }
  },
  methods: {
    init (info) {
      this.visible = true
      this.loading = this.$loading({ text: '加载中' })
      this.$http.get('dept/list').then(({ data }) => {
        if (data.code === 20000) {
          this.deptList = this.formatterTreeData(data.data)
          this.loading.close()
          if (info) {
            this.title = '修改部门'
            const updateInfo = {
              id: info.id,
              fullname: info.fullname,
              simplename: info.simplename,
              pid: info.pid,
              num: info.num
            }
            this.deptInfo = updateInfo
          } else {
            this.title = '添加部门'
            this.deptInfo = { ...initInfo }
          }
        }
      })
    },
    formatterTreeData (arr) {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].children.length === 0) {
          arr[i].children = undefined
        } else {
          this.formatterTreeData(arr[i].children)
        }
      }
      return arr
    },
    save () {
      this.$http.post('dept', this.deptInfo).then((res) => {
        if (res.data && res.data.code === 20000) {
          this.$message({
            message: this.deptInfo.id ? '修改成功' : '添加成功',
            type: 'success',
            onClose: () => {
              this.visible = false
              this.$emit('reloadTable')
            }
          })
        } else {
          this.$alert('操作失败', { type: 'error' })
        }
      }).catch((err) => {
        const data = err.response.data
        this.$alert(data.message, { type: 'error' })
      })
    }
  }
}
</script>

<style scoped>

</style>
